﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using BLL;
using DLL;
using Core;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.Configuration;
using CommonHelpers;

namespace QuanLyBanLe.Admin
{
    public partial class FormGenerateBarcode : Form
    {
        private ProducerService m_ProducerService;
        private ProductTypeService m_ProductTypeService;
        private ProductService m_ProductService;
        private InProductService m_InOutProductService;
        private IList<Producer> m_Producers;
        private IList<ProductType> m_ProductTypes;
        private IList<Product> m_Products;
        private bool m_LoadComplete;
        private int m_Copies;
        private Image m_BarCodeImage;
        private bool m_CloseFromPrint;
        private const int SpaceSize = 110;
        private const int LabelHeight = 108;
        private const int LabelWidth = 135;
        private bool m_HasListPrice;

        public FormGenerateBarcode()
        {
            m_ProducerService = new ProducerService();
            m_ProductTypeService = new ProductTypeService();
            m_ProductService = new ProductService();
            m_InOutProductService = new InProductService();
            m_LoadComplete = false;
            m_CloseFromPrint = false;
            InitializeComponent();
            m_HasListPrice = false;
        }

        private void FormGenerateBarcode_Load(object sender, EventArgs e)
        {
            lblSalePrice.Text = "0 Đ";
            m_Producers = m_ProducerService.GetProducers();
            m_ProductTypes = m_ProductTypeService.GetProductTypes();
            SetProductType();
            SetProducer();
            SetProducts();
            SetAutoCompleteForCombobox();
            this.Text += FormMain.GetShopInfo();            
            m_LoadComplete = true;
        }

        private void SetProductType()
        {
            var productTypes = new List<ProductType>();
            productTypes.Add(new ProductType() { Id = 0, Name = "Tất cả" });
            productTypes.AddRange(m_ProductTypes);
            cboProductType.DataSource = productTypes;
        }

        private void SetProducer()
        {
            var producers = new List<Producer>();
            producers.Add(new Producer() { Id = 0, Name = "Tất cả" });
            producers.AddRange(m_Producers);
            cboProducer.DataSource = producers;
        }

        private void SetProducts()
        {
            m_Products = m_ProductService.GetProducts();
            cboProduct.DataSource = m_Products;
            SetSalePrice();
        }

        private void SetAutoCompleteForCombobox()
        {
            cboProductType.DropDownStyle = ComboBoxStyle.DropDown;
            cboProductType.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cboProductType.AutoCompleteSource = AutoCompleteSource.ListItems;

            cboProducer.DropDownStyle = ComboBoxStyle.DropDown;
            cboProducer.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cboProducer.AutoCompleteSource = AutoCompleteSource.ListItems;

            SetAutoCompleteForProductCombobox();
        }

        private void SetAutoCompleteForProductCombobox()
        {
            cboProduct.DropDownStyle = ComboBoxStyle.DropDown;
            cboProduct.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
            cboProduct.AutoCompleteSource = AutoCompleteSource.ListItems;
        }

        private void cboProductType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (m_LoadComplete)
            {
                m_Products = m_ProductService.GetProductsByTypeAndProducer(Convert.ToInt32(cboProductType.SelectedValue), Convert.ToInt32(cboProducer.SelectedValue));
                cboProduct.DataSource = m_Products;
                SetAutoCompleteForProductCombobox();
            }
        }

        private void cboProducer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (m_LoadComplete)
            {
                m_Products = m_ProductService.GetProductsByTypeAndProducer(Convert.ToInt32(cboProductType.SelectedValue), Convert.ToInt32(cboProducer.SelectedValue));
                cboProduct.DataSource = m_Products;
                SetAutoCompleteForProductCombobox();
            }
        }

        private void cboProductType_Click(object sender, EventArgs e)
        {
            SetProductType();
            cboProduct.Text = "";
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnGenerate_Click(object sender, EventArgs e)
        {
            if (!CheckError())
            {
                errorProvider.SetError(cboProduct, "");
                int productId = Convert.ToInt32(cboProduct.SelectedValue);
                var product = m_Products.Where(x => x.Id == productId).FirstOrDefault();
                if (product.SalePrice.HasValue)
                {
                    string code = "";
                    m_BarCodeImage = BarCode.CreateBarCode(productId.ToString(), product.Name, product.SalePrice, product.ListedPrice, ref code, FormMain.s_OS);
                    if (product.ListedPrice.HasValue && product.ListedPrice > 0)
                    {
                        m_HasListPrice = true;
                    }
                    PrintBarCode();
                    this.Close();
                }
                else
                {
                    MessageBox.Show("Chưa nhập giá bán cho sản phẩm");
                }
            }
        }

        private bool CheckError()
        {
            bool isError = false;
            if (cboProduct.SelectedValue == null)
            {
                errorProvider.SetError(cboProduct, "Vui lòng chọn sản phẩm");
                isError = true;
            }
            else
            {
                errorProvider.SetError(cboProduct, "");
            }

            if (string.IsNullOrEmpty(ntbAmount.Text))
            {
                isError = true;
                errorProvider.SetError(ntbAmount, "Vui lòng chọn điền thông tin");
            }
            else
            {
                errorProvider.SetError(ntbAmount, "");
            }

            return isError;
        }


        private void PrintBarCode()
        {
            try
            {
                Font printFont = new Font("Arial", 10);
                PrintDocument pd = new PrintDocument();
                m_Copies = Convert.ToInt32(ntbAmount.Text);
                m_Copies = m_Copies / 2 + m_Copies % 2;
                pd.DefaultPageSettings.PaperSize = new PaperSize("Label", 310, LabelHeight * m_Copies);
                pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
                pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
                pd.BeginPrint += new PrintEventHandler(pd_BeginPrint);
                pd.EndPrint += new PrintEventHandler(pd_EndPrint);
                string barcodePrinter = ConfigurationManager.AppSettings["BarcodePrinterName"];
                if (!string.IsNullOrEmpty(barcodePrinter))
                {
                    pd.PrinterSettings.PrinterName = barcodePrinter;
                }
                pd.Print();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void pd_EndPrint(object sender, PrintEventArgs e)
        {
            
        }

        private void pd_BeginPrint(object sender, PrintEventArgs e)
        {
            
        }

        void pd_PrintPage(object sender, PrintPageEventArgs ev)
        {
            int marginTop = 25;
            if (m_HasListPrice)
            {
                marginTop = 20;
            }
            for (int i = 0; i < m_Copies; i++)
            {
                ev.Graphics.DrawImage(m_BarCodeImage, 10, marginTop + i * LabelHeight, LabelWidth, LabelHeight);
                ev.Graphics.DrawImage(m_BarCodeImage, 155, marginTop + i * LabelHeight, LabelWidth, LabelHeight);
            }
            m_CloseFromPrint = true;
        }

        private void FormGenerateBarcode_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (m_CloseFromPrint)
            {
                m_CloseFromPrint = false;
                e.Cancel = true;
            }
        }

        private void cbo_KeyDown(object sender, KeyEventArgs e)
        {
            ComboBox cbo = sender as ComboBox;
            if (cbo.DroppedDown)
            {
                cbo.DroppedDown = false;
            }
        }

        private void cboProduct_SelectedIndexChanged(object sender, EventArgs e)
        {
            SetSalePrice();
        }

        private void SetSalePrice()
        {
            int productId = Convert.ToInt32(cboProduct.SelectedValue);
            var product = m_Products.Where(x => x.Id == productId).FirstOrDefault();
            if (product.SalePrice.HasValue)
            {
                lblSalePrice.Text = product.SalePrice.Value.ToMoney();
            }
            else
            {
                lblSalePrice.Text = "0 Đ";
            }
        }
    }
}
